﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OGS.Contracts;
using OGS.Utility;
using OGS.Web.Models.Admin;
using Newtonsoft.Json;
using System.Data.Odbc;
using System.Data;
using System.IO;

namespace OGS.Web.Controllers.Admin
{
    public partial class AdminController : AdminBaseController
    {
        /// <summary>
        /// User list
        /// </summary>
        /// <param name="Name"></param>
        /// <returns></returns>
        [ActionName("user-list")]
        public ActionResult UserList()
        {

            SearchAttributes SearchAttributes = new SearchAttributes();
            SearchAttributes.CurrentPageNumber = Helper.GetQueryStringValueInt("page");
            SearchAttributes.CurrentPageNumber = SearchAttributes.CurrentPageNumber == 0 ? 1 : SearchAttributes.CurrentPageNumber;
            SearchAttributes.SortColumnIndex = Helper.GetQueryStringValueInt("SortColumnIndex");
            SearchAttributes.SortDirection = (SortDirection)Helper.GetQueryStringValueInt("SortDirection");
            SearchAttributes.RecordsPerPage = Settings.RecordsPerPage;

            UserListModel oUserModel = new UserListModel();
            oUserModel.PopulateRoles();
            oUserModel.Role.Insert(0, new Role { RoleID = 0, Name = "All" });
            oUserModel.Populate(string.Empty, SearchAttributes);
            oUserModel.SearchAttributes = SearchAttributes;
            oUserModel.Search1 = string.Empty;



            return View("~/Views/Admin/User/UserList.aspx", oUserModel);
        }

        [HttpPost]
        public ActionResult UserList(string Search1, string Search2, string Search3)
        {
            Search1 = Search1 == null ? string.Empty : Search1.Trim();
            Search2 = Search2 == null ? string.Empty : Search2.Trim();
            Search3 = Search3 == null ? string.Empty : Search3.Trim();

            SearchAttributes SearchAttributes = new SearchAttributes();
            SearchAttributes.CurrentPageNumber = Helper.GetQueryStringValueInt("page");
            SearchAttributes.CurrentPageNumber = SearchAttributes.CurrentPageNumber == 0 ? 1 : SearchAttributes.CurrentPageNumber;
            SearchAttributes.SortColumnIndex = Helper.GetQueryStringValueInt("SortColumnIndex");
            SearchAttributes.SortDirection = (SortDirection)Helper.GetQueryStringValueInt("SortDirection");
            SearchAttributes.RecordsPerPage = Settings.RecordsPerPage;

            UserListModel oUserModel = new UserListModel();
            oUserModel.PopulateRoles();
            oUserModel.Role.Insert(0, new Role { RoleID = 0, Name = "All" });
            oUserModel.Populate(Search1, SearchAttributes);
            oUserModel.SearchAttributes = SearchAttributes;
            oUserModel.Search1 = Search1;



            return View("~/Views/Admin/User/UserList.aspx", oUserModel);
        }
        /// <summary>
        /// Save Brand Action Result
        /// </summary>
        /// <returns></returns>
        [ActionName("save-user")]
        public ActionResult SaveUser(int? ID)
        {
            SaveUserModel oSaveUserModel = new SaveUserModel();
            oSaveUserModel.IsActive = true;
            if (ID.HasValue)
            {
                //Get User from DB
                oSaveUserModel.GetUserDetails(ID.Value);

                oSaveUserModel.IsSuccess = Session["Success"] == null ? false : true;
                Session["Success"] = null;

            }
            oSaveUserModel.PopulateRoles();
            oSaveUserModel.Role.Insert(0, new Role { RoleID = 0, Name = "--- Select ---" });
            return View("~/Views/Admin/User/SaveUser.aspx", oSaveUserModel);
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ActionName("save-user")]
        public ActionResult SaveUser(SaveUserModel oSaveUserModel)
        {
            if (ModelState.IsValid)
            {
                Result result = (Result)oSaveUserModel.SaveUser();
                if (result == Result.Success)
                {
                    Session["Success"] = true;
                    return Redirect("/admin/save-user/" + oSaveUserModel.ID.ToString());
                }
                else if (result == Result.Duplicate)
                {
                    ModelState.AddModelError("Name", "The name already exists.");
                }
                else
                {
                    ModelState.AddModelError("Name", "Some error occurred. Please try again later.");
                }

            }
            return View("~/Views/Admin/User/SaveUser.aspx", oSaveUserModel);
        }
        [HttpGet]
        public JsonResult GetPostalCodes(string PostalCode)
        {
            List<Zips> listZip = new List<Zips>();
            try
            {
                using (StreamReader reader = new StreamReader(HttpRuntime.AppDomainAppPath.ToString() + @"PostalCodes\PostalCodes.txt"))
                {
                    string line;
                    int countZips = 0;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (countZips > 0)
                        {
                            Zips oZip = new Zips();
                            oZip.id = line.Split(new char[] { (char)9 })[1];
                            oZip.value = line.Split(new char[] { (char)9 })[1];
                            listZip.Add(oZip);
                        }
                        countZips++;
                    }
                }
            }
            catch  //Error
            {
            }

           listZip = listZip.Where(s => s.id.ToLower().Contains(PostalCode.ToLower())).Select(w => w).ToList();

            var json = JsonConvert.SerializeObject(listZip.Distinct().ToList(), new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
            return Json(json, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public JsonResult GetAreaByPostalCodes(string PostalCode)
        {
            //List<Area> lstArea = Utility.PostCodeHelper.GetAreas(PostalCode);
            List<Areas> listArea = new List<Areas>();
            try
            {
                using (StreamReader reader = new StreamReader(HttpRuntime.AppDomainAppPath.ToString() + @"PostalCodes\PostalCodes.txt"))
                {
                    string line;
                    int countZips = 0;
                    while ((line = reader.ReadLine()) != null)
                    {
                        if (countZips > 0)
                        {
                            Areas oArea = new Areas();
                            oArea.Zip = line.Split(new char[] { (char)9 })[1];
                            oArea.AreaName= line.Split(new char[] { (char)9 })[0];
                            oArea.State = line.Split(new char[] { (char)9 })[2];
                            listArea.Add(oArea);
                        }
                        countZips++;
                    }
                }
            }
            catch  //Error
            {
            }

            var filtered = from area in listArea
                             where area.Zip == PostalCode
                             select area;

            var json = JsonConvert.SerializeObject(filtered.Distinct().ToList(), new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
            return Json(json, JsonRequestBehavior.AllowGet);
        }
    }
}